package com.logistic.server.common.aspect;


import com.logistic.server.common.annotation.HasPermissions;
import com.logistic.server.common.exception.ForbiddenException;
import com.logistic.server.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 权限切点
 *
 * @author swen
 */
@Aspect
@Component
@Slf4j
public class PreAuthorizeAspect {

    @Around("@annotation(com.logistic.server.common.annotation.HasPermissions)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        HasPermissions annotation = method.getAnnotation(HasPermissions.class);
        if (annotation == null) {
            return point.proceed();
        }
        String authority = annotation.value();
        if (has(authority)) {
            return point.proceed();
        } else {
            throw new ForbiddenException();
        }
    }

    // 根据用户查询用户对应的权限
    private boolean has(String authority) {
        return Objects.requireNonNull(SecurityUtils.getLoginUser()).getPermissions().contains(authority);
    }
}
